package xyz.iguilty.documents.doc.view;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.view.AbstractTemplateView;
import xyz.iguilty.documents.common.constant.DocumentConstant;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;


public class WordTemplateView extends AbstractTemplateView {

    @Override
    protected void renderMergedTemplateModel(Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) throws Exception {
        try (ServletOutputStream outputStream = response.getOutputStream()
        ) {
            String filename = String.format("%s_%s.docx", map.containsKey(DocumentConstant.FILENAME) ? String.valueOf(map.get(DocumentConstant.FILENAME)) : this.getBeanName(), new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            ConfigureBuilder builder = null;
            if (map.containsKey(DocumentConstant.WORD_CONFIG)){
                 Object configObject = map.get(DocumentConstant.WORD_CONFIG);
                 if (configObject instanceof ConfigureBuilder){
                     builder = (ConfigureBuilder) configObject;
                 }else {
                     throw new IllegalArgumentException("参数config类型必须为com.deepoove.poi.config.ConfigureBuilder");
                 }
            }else {
                builder = Configure.builder();
            }
            builder.useSpringEL(); //使用SpringEL表达式
            builder.buildGramer("${", "}");//使用${}获得参数
            XWPFTemplate template = XWPFTemplate.compile(new ClassPathResource(Objects.requireNonNull(this.getUrl())).getFile(),builder.build()).render(map);
            template.write(outputStream);
        }
    }

    @Override
    public boolean checkResource(Locale locale){
        boolean isExist = false;
        try {
            isExist = new ClassPathResource(Objects.requireNonNull(this.getUrl())).getFile().exists();
        } catch (IOException ignored) {
        }
        return isExist;
    }
}
